package com.zff.rental.repository.apartment;

import com.zff.rental.entity.apartment.TrRoomDeviceEntity;
import com.zff.rental.utils.collectors.CollectionsUtils;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author HCY
 */
@Repository
public interface TrRoomDeviceRepository extends JpaRepository<TrRoomDeviceEntity, TrRoomDeviceEntity> {
    default List<TrRoomDeviceEntity> saveAllOrDelete(Long roomId, List<Long> newIdList) {
        if (newIdList != null) {
            if (newIdList.isEmpty()) {
                deleteAllByRoomId(roomId);
            } else {
                List<TrRoomDeviceEntity> oldList = findAllByRoomId(roomId);
                List<Long> oldIdList = oldList.stream().map(TrRoomDeviceEntity::getDeviceId).toList();

                List<Long> delIdList = CollectionsUtils.reduceToList(oldIdList, newIdList);
                List<TrRoomDeviceEntity> addList = CollectionsUtils.reduceToList(newIdList, oldIdList).stream()
                        .map(deviceId -> new TrRoomDeviceEntity(roomId, deviceId))
                        .collect(Collectors.toList());

                if (!delIdList.isEmpty()) {
                    deleteByRoomIdAndDeviceIdIn(roomId, delIdList);
                }
                if (!addList.isEmpty()) {
                    saveAll(addList);
                }
            }
        }
        return findAllByRoomId(roomId);
    }

    void deleteByRoomIdAndDeviceIdIn(Long roomId, List<Long> delIdList);

    List<TrRoomDeviceEntity> findAllByRoomId(Long roomId);

    List<TrRoomDeviceEntity> findAllByRoomIdIn(List<Long> roomIdList);

    void deleteAllByRoomId(Long id);
}
